package com.wen.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wen.common.R;
import com.wen.pojo.Merchant;
import com.wen.pojo.Orders;
import com.wen.pojo.dto.*;
import com.wen.pojo.*;
import com.wen.pojo.dto.OrdersDto;
import com.wen.pojo.dto.wen.*;
import com.wen.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wen.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xie
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/Orders")
public class OrdersController {

    @Autowired
    private OrdersService service;

    @PostMapping("sel/{pageNum}/{pageSize}")
    public R sel(@RequestBody OrdersDtoTiaoJian dto, @PathVariable Integer pageNum, @PathVariable Integer pageSize) {

        Page<OrdersDto> sel = service.sel(dto, pageNum, pageSize);

        return R.ok().data("records", sel.getRecords()).
                data("total", sel.getTotal()).
                data("current", sel.getCurrent()).
                data("size", sel.getSize());
    }

    /**
     * 订单管理模块（订单查询）
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @PostMapping("selAll/{pageNum}/{pageSize}")
    public R selAll(@RequestBody OrdersANDConsumerANDMerchantDto dto, @PathVariable Integer pageNum, @PathVariable Integer pageSize) {

        Page<OrdersANDConsumerANDMerchants> page = service.selAll(dto, pageNum, pageSize);


        return R.ok().data("records", page.getRecords()).
                data("total", page.getTotal()).
                data("current", page.getCurrent()).
                data("size", page.getSize());
    }

    /**
     * 订单管理模块（订单查询中的订单详情）
     *
     * @param id
     * @return
     */
    @GetMapping("selById/{id}")
    public R selById(@PathVariable String id) {
        Orders byId = service.getById(id);
        return R.ok().data("selById", byId);
    }

    @PostMapping("seldb/{pageNum}/{pageSize}")
    public R seldb(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        Page<DiaoBos> page = service.seldb(pageNum, pageSize);
        return R.ok().data("records", page.getRecords()).
                data("total", page.getTotal()).
                data("current", page.getCurrent()).
                data("size", page.getSize());
    }

    @PostMapping("/pro2/{pageNum}/{pageSize}")
    public R pro2(Page<TransferGoods> pageParam,
                  @RequestBody TransferGoodsDto dto,
                  @PathVariable Long pageNum,
                  @PathVariable Long pageSize) {
        IPage<TransferGoods> iPage = service.searchPage2(pageParam, dto, pageNum, pageSize);
        return R.ok().data("files", iPage.getRecords())
                .data("total", iPage.getTotal())//总记录数
                .data("current", iPage.getCurrent()) //当前页号
                .data("size", iPage.getSize());//页大小
    }

    @PostMapping("/selectOrder/{id}")
    public R selectOrder(@PathVariable String id) {
        List<OrderDetails2> list = service.OrderDetailslist(id);
        Orders2 purchaseOrder = service.ordersByid(id);
        return R.ok().data("list", list).data("bean", purchaseOrder);
    }

    @PostMapping("/add/{totalPrice}/{amout}/{register}/{id}")
    public R add(@RequestBody List<OrderDetails2> list,
                 @PathVariable("totalPrice") String totalPrice,
                 @PathVariable("amout") String amout,
                 @PathVariable("register") String register,
                 @PathVariable("id") String id) {

        Pay pay = new Pay();
        pay.setPayOrderNumber("400202304120002");
        pay.setReason("r001-1");
        pay.setTotalAmount(Integer.valueOf(amout));
        pay.setTotalPrice(Double.parseDouble(totalPrice));
        pay.setRegister(register);
        pay.setRegisterTime(new Date());
        pay.setCheckTag("s001-1");
        service.addPay(pay);
        int count = 0;
        List<PayDetails> stockDetails = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {


            List<StockDetails> list1 = service.stocklist();
            int payamout = list.get(i).getAmount();

            for (int j = 0; j < list1.size(); j++) {


                if (list1.get(j).getRealAmount() >= payamout && list1.get(j).getProductId() == list.get(i).getProductId()) {
                    System.out.println(list1.get(j).getRealAmount() + "大于" + payamout);
                    PayDetails payDetails = new PayDetails();
                    payDetails.setPayId(pay.getPayId());
                    payDetails.setStockId((int) list1.get(j).getStockId());
                    payDetails.setProductId(list.get(i).getProductId());
                    payDetails.setPrice(list.get(i).getPrice());
                    int taosub = (int) (payamout * list.get(i).getPrice());
                    payDetails.setSubTotal(taosub);
                    payDetails.setAmount(payamout);

                    service.addPayDetails(payDetails);
                    service.upStock(payDetails);
                    stockDetails.add(payDetails);

                    count++;
                    break;
                } else if (list1.get(j).getRealAmount() < payamout && list1.get(j).getProductId() == list.get(i).getProductId() && list1.get(j).getRealAmount() != 0) {
                    System.out.println(list1.get(j).getRealAmount() + "小于" + payamout);
                    PayDetails payDetails = new PayDetails();
                    payDetails.setPayId(pay.getPayId());
                    payDetails.setStockId((int) list1.get(j).getStockId());
                    payDetails.setProductId(list.get(i).getProductId());

                    payDetails.setPrice(list.get(i).getPrice());
                    int taosub = (int) (list1.get(j).getRealAmount() * list.get(i).getPrice());
                    payDetails.setSubTotal(taosub);
                    payamout = payamout - (int) list1.get(j).getRealAmount();
                    payDetails.setAmount(payamout);
                    list1.get(j).setRealAmount(0);
                    service.upStock(payDetails);
                    service.addPayDetails(payDetails);
                    stockDetails.add(payDetails);
                    count++;
                }

            }
        }
        for (int i = 0; i < stockDetails.size(); i++) {
            service.upStock2(stockDetails.get(i));
        }

        service.upOrderState(id);

        return R.ok().data("fls", count);
    }

    @PostMapping("page1/{pageNum}/{pageSize}")
    public R selOrderState1(@PathVariable Long pageNum,
                            @PathVariable Long pageSize) {
        IPage<OrdersDto> ordersDtoIPage = service.selOrderState1(pageNum, pageSize);
        return R.ok().data("records", ordersDtoIPage.getRecords())
                .data("total", ordersDtoIPage.getTotal())//总记录数
                .data("current", ordersDtoIPage.getCurrent()) //当前页号
                .data("size", ordersDtoIPage.getSize());//页大小;
    }

    @PostMapping("page2/{pageNum}/{pageSize}")
    public R selOrderState2(@PathVariable Long pageNum,
                            @PathVariable Long pageSize) {
        IPage<OrdersDto> ordersDtoIPage = service.selOrderState2(pageNum, pageSize);
        return R.ok().data("records", ordersDtoIPage.getRecords())
                .data("total", ordersDtoIPage.getTotal())//总记录数
                .data("current", ordersDtoIPage.getCurrent()) //当前页号
                .data("size", ordersDtoIPage.getSize());//页大小;
    }

    @PostMapping("page3/{pageNum}/{pageSize}")
    public R selOrderState3(@PathVariable Long pageNum,
                            @PathVariable Long pageSize) {
        IPage<OrdersDto> ordersDtoIPage = service.selOrderState3(pageNum, pageSize);
        return R.ok().data("records", ordersDtoIPage.getRecords())
                .data("total", ordersDtoIPage.getTotal())//总记录数
                .data("current", ordersDtoIPage.getCurrent()) //当前页号
                .data("size", ordersDtoIPage.getSize());//页大小;
    }

    @PostMapping("upOrderState3/{id}")
    public R upOrderState3(@PathVariable String id){
        Boolean aBoolean = service.upOrderState3(id);
        return R.ok().message("成功");
    }


    @PostMapping("/AddQuery")
    public R AddQuery(@RequestBody OrdersDto dto){

        int or = service.Or(dto);

        if (or >0) {
            return R.ok().message("添加成功！");
        }
        return R.error().message("添加失败！");
    }



    @PostMapping("/ProductAndOrdersAndOrdersDetails")
    public R querypageTwo(@RequestBody ProductAndOrdersAndOrdersDetailsDto dto){
        System.out.println(dto);
        Page<ProductAndOrdersAndOrdersDetails> medicinesPage = service.getSelectAll(dto);
        return R.ok().data("records",medicinesPage.getRecords())
                .data("total",medicinesPage.getTotal())
                .data("current",medicinesPage.getCurrent())
                .data("size",medicinesPage.getSize());

    }

    @PostMapping("/OrderAll")
    public R OrderAll(@RequestBody ProductAndOrdersAndOrdersDetailsDto dto){
        System.out.println(dto);
        Page<OrderAll> selectOrderAll = service.getSelectOrderAll(dto);
        return R.ok().data("records",selectOrderAll.getRecords())
                .data("total",selectOrderAll.getTotal())
                .data("current",selectOrderAll.getCurrent())
                .data("size",selectOrderAll.getSize());

    }

    @GetMapping("/selectOrderById/{id}")
    public R selectOrderById(@PathVariable Integer id){
        List<OrderAll> selectOrderById = service.getSelectOrderById(id);
        return R.ok().data("selectOrderById",selectOrderById);
    }






}
